package com.anjingsi.tools;

import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @program: plat-user
 * @description
 * @author: 安静思
 * @create: 2019-07-18 13:58
 **/
@Slf4j
public class CheckParamUtil {

    private static final String EMAIL_REGEX = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?";

    private static final String serialVersionUID = "serialVersionUID";
    /**
     * 参数验证
     * @param t
     * @param <T>
     */
    public static <T> void checkParam(T t) throws Exception {
        if (t == null) {
            throw new RuntimeException("参数不能为空",null);
        }
        Class<? extends Object> clazz = t.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if(field.getName().equals(serialVersionUID)){
                continue;
            }
            //获取当前属性的值
            Method method = clazz.getMethod("get"+acronymToUpper(field.getName()), new Class[] {});
            Object value = method.invoke(t, new Object[] {});
            NotBlank notblank = field.getDeclaredAnnotation(NotBlank.class);
            if(notblank != null && null == value){
                throw new RuntimeException(notblank.message());
            }
            NotNull notNull = field.getDeclaredAnnotation(NotNull.class);
            if(notNull != null && null == value){
                throw new RuntimeException(notblank.message());
            }
            Pattern pattern = field.getDeclaredAnnotation(Pattern.class);
            if(pattern != null){
                if(value == null){
                    throw new RuntimeException(notblank.message());
                }
                boolean matches = value.toString().matches(pattern.regexp());
                if(!matches){
                    throw new RuntimeException("格式错误");
                }
            }
            Email email = field.getDeclaredAnnotation(Email.class);
            if(email != null){
                if(value == null){
                    throw new RuntimeException(email.message());
                }
                boolean matches = value.toString().matches(EMAIL_REGEX);
                if(!matches){
                    throw new RuntimeException("邮箱格式不正确");
                }
            }
        }
    }


    private static String acronymToUpper(String str){
        char[] chars = str.toCharArray();
        if (chars[0] >= 'a' && chars[0] <= 'z') {
            chars[0] = (char) (chars[0] - 32);
        }
        return new String(chars);
    }
}
